package net.reea.example.multiselect;

import java.util.ArrayList;
import java.util.HashSet;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import com.example.smallandroidcodetester.R;

public final class MultiSelectionListAdapter extends BaseAdapter {
	private static final String TAG = MultiSelectionListAdapter.class.getSimpleName();
	private LayoutInflater inflater;
	private ArrayList<String> items;

	// all our checked indexes go here
	private HashSet<Integer> checkedItems;

	// multi selection mode flag
	private boolean multiMode;

	public MultiSelectionListAdapter(Context context, ArrayList<String> items) {
		this.inflater = LayoutInflater.from(context);
		this.items = items;
		this.checkedItems = new HashSet<Integer>();
	}

	public void enterMultiMode() {
		multiMode = true;
		notifyDataSetChanged();
	}

	public void exitMultiMode() {
		checkedItems.clear();
		multiMode = false;
		notifyDataSetChanged();
	}

	public void setChecked(int pos, boolean checked) {
		if (checked) {
			checkedItems.add(Integer.valueOf(pos));
		} else {
			checkedItems.remove(Integer.valueOf(pos));
		}
		if (multiMode) {
			notifyDataSetChanged();
		}
	}

	public void toggleChecked(int pos) {
		final Integer v = Integer.valueOf(pos);
		if (this.checkedItems.contains(v)) {
			this.checkedItems.remove(v);
		} else {
			this.checkedItems.add(v);
		}
		this.notifyDataSetChanged();
	}

	public int getCheckedItemCount() {
		return this.checkedItems.size();
	}

	@Override
	public int getCount() {
		return items.size();
	}

	@Override
	public String getItem(int position) {
		return items.get(position);
	}

	@Override
	public long getItemId(int position) {
		return 0;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		if (convertView == null) {
			convertView = inflater.inflate(R.layout.list_multi_choice_item, null);
			// convert view stuff cleared, to much code - do the usual Holder stuff here
		}

		TextView tv = (TextView) convertView.findViewById(R.id.ListItemTitle);
		tv.setText(items.get(position));

		// the 4 state change problem described above. We use a second selector with no pressed state color if in multi mode
		convertView.setBackgroundResource(this.multiMode ? R.drawable.selector_list_multimode : R.drawable.selector_list);

		if (checkedItems.contains(Integer.valueOf(position))) {
			// if this item is checked - set checked state
			convertView.getBackground().setState(new int[] { android.R.attr.state_checked });
		} else {
			// if this item is unchecked - set unchecked state (notice the minus)
			convertView.getBackground().setState(new int[] { -android.R.attr.state_checked });
		}

		return convertView;
	}

}